package edu.fight.utils;

import edu.fight.dto.JwtUser;
import edu.fight.utils.jwt.JwtUtils;
import edu.fight.utils.jwt.RsaFileInMemory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class RequestContextUtil {

    /**
     *
     * @return
     */
    public JwtUser getJwtUserFromRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        JwtUser jwtUser=null;
        try {
            jwtUser = JwtUtils.getInfoFromToken(token, RsaFileInMemory.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }

        return jwtUser;
    }
}
